﻿using Ninject;
using Nx.Logging;
using Nx.ViewModels;
#if !NETFX_CORE
using System.Windows;
#else
using Windows.UI.Xaml;
#endif

namespace Nx.Kernel
{
    public static class IKernelExtensionsUI
    {
        /// <summary>
        /// Configures View-ViewModel mapping. When resolving the ViewModel, the Kernel will return a ViewModel with the matching View
        /// </summary>
        /// <typeparam name="TView">FrameworkElement containing the DataContext property</typeparam>
        /// <typeparam name="TViewModel">ViewModel deriving from ViewModelBase</typeparam>
        /// <param name="kernel">The kernel</param>
        /// <param name="key">Mapping key</param>
        public static void ConfigureVVMMapping<TView, TViewModel>(this IKernel kernel, string key)
            where TView : FrameworkElement
            where TViewModel : ViewModelBase
        {
            using (ILogger log = kernel.GetLogger("SYSTEM"))
            {
                kernel.Bind<TView>().ToSelf().InTransientScope().Named(key);
                kernel.Bind<TViewModel>().ToSelf().InTransientScope()
                    .OnActivation((vm) =>
                    {
                        (vm as ViewModelBase).View = kernel.Get<TView>(key);
                        ((vm as ViewModelBase).View as FrameworkElement).DataContext = vm;
                    });
                log.Debug("V-VM Mapping : {0} -> {1}", typeof(TView).Name, typeof(TViewModel).Name);
            }
        }

        public static void ConfigureShellVVMMapping<TView, IShell, TShellViewModel>(this IKernel kernel, string key)
            where TView : FrameworkElement
            where TShellViewModel : ViewModelBase, IShell
        {
            using (ILogger log = kernel.GetLogger("SYSTEM"))
            {
                kernel.Bind<TView>().ToSelf().InTransientScope().Named(key);
                kernel.Bind<IShell, TShellViewModel>().To<TShellViewModel>().InSingletonScope()
                    .OnActivation((vm) =>
                    {
                        (vm as ViewModelBase).View = kernel.Get<TView>(key);
                        ((vm as ViewModelBase).View as FrameworkElement).DataContext = vm;
                    });
                log.Debug("Shell V-VM Mapping : {0} -> {1}", typeof(TView).Name, typeof(TShellViewModel).Name);
            }
        }
    }
}
